--[[
	背包界面
	2016_07_06 Ravioyla
]]

local KeFuLayer = class("KeFuLayer", function(scene)
		local bagLayer = display.newLayer(cc.c4b(0, 0, 0, 125))
    return bagLayer
end)
local ExternalFun = appdf.req(appdf.EXTERNAL_SRC .. "ExternalFun")
local HeadSprite = appdf.req(appdf.EXTERNAL_SRC .. "HeadSprite")
local utils = appdf.req(appdf.EXTERNAL_SRC .. "Utils")

KeFuLayer.BT_FAQ = 1
KeFuLayer.BT_FEEDBACK = 2
KeFuLayer.BT_SENDFEEDBACK = 3
-- 进入场景而且过渡动画结束时候触发。
function KeFuLayer:onEnterTransitionFinish()
		--自动跳转
	
	
    return self
end
local scheduler = cc.Director:getInstance():getScheduler()  
-- 退出场景而且开始过渡动画时候触发。
function KeFuLayer:onExitTransitionStart()
	if self.schedulerID then
		cc.Director:getInstance():getScheduler():unscheduleScriptEntry(self.schedulerID)
	end
	 
    return self
end

function KeFuLayer:ctor(scene)
	self:registerScriptHandler(function(eventType)
		if eventType == "enterTransitionFinish" then	-- 进入场景而且过渡动画结束时候触发。
			self:onEnterTransitionFinish()
		elseif eventType == "exitTransitionStart" then	-- 退出场景而且开始过渡动画时候触发。
			self:onExitTransitionStart()
        elseif eventType == "exit" then
        
		end
	end)


	self.scene = scene
		
		local rootLayer, csbNode = ExternalFun.loadRootCSB( "kefu/kefuLayer.csb", self )
		self.csbNode = csbNode
		ExternalFun.FixTopUI(csbNode)
		self.csbNode:setPositionY((display.height-750)/2)
		csbNode:getChildByName("keyback_btn"):addTouchEventListener(function(ref,type) 
		if type == ccui.TouchEventType.ended then
			ExternalFun.playClickEffect( )
			scene.KeFuLay = nil
			--self:removeFromParent()
			scene:onKeyBack()
			ref:setScale(1)
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then  
			ref:setScale(1)
		end
		end)
	local btcallback = function (ref, type)
		if type == ccui.TouchEventType.ended then
			ExternalFun.playClickEffect( )
			self:onButtonClickedEvent(ref:getTag(),ref)
			ref:setScale(1)
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then  
			ref:setScale(1)
		end
	end

	self.feedback_panel = csbNode:getChildByName("feedback_panel")
	
	self.FAQ_panel = csbNode:getChildByName("FAQ_panel")
	
	self.FAQ_btn = csbNode:getChildByName("FAQ_btn")
	self.feedback_btn = csbNode:getChildByName("feedback_btn")
	
	self.FAQ_btn:setTag(KeFuLayer.BT_FAQ)
	self.feedback_btn:setTag(KeFuLayer.BT_FEEDBACK)
	self.FAQ_btn:addTouchEventListener(btcallback)
	self.feedback_btn:addTouchEventListener(btcallback)
	
	self.feedchatList = self.feedback_panel:getChildByName("chatListview")
	
	local send_btn = self.feedback_panel:getChildByName("send_btn")
	send_btn:setTag(KeFuLayer.BT_SENDFEEDBACK)
	send_btn:addTouchEventListener(btcallback)
	self.send_btn = send_btn
	self.sendAtlas = send_btn:getChildByName("sendAtlas")
	local lastSendFeedBackTime = cc.UserDefault:getInstance():getIntegerForKey("feedbacklimit", 0)
	local remainTime = os.time() - lastSendFeedBackTime
	if remainTime >120 then
		self.send_btn:setEnabled(true)
		self.sendAtlas:setVisible(false)
	else
		sec = 120 - remainTime
		self.sendAtlas:setString(sec)
		self.send_btn:setEnabled(false)
		self.sendAtlas:setVisible(true)
		self.schedulerID = scheduler:scheduleScriptFunc( function()
            sec = sec - 1
            if not tolua.isnull(self.send_btn) then
				self.sendAtlas:setString(sec)
           --     self.send_btn:setTitleText("重发（" .. sec .. "）")
                if sec <= 0 then
                    cc.Director:getInstance():getScheduler():unscheduleScriptEntry(self.schedulerID)
                    self.send_btn:setEnabled(true)
					self.sendAtlas:setVisible(false)
                end        
            end      
        end , 1, false)
	end
	local cunTemp_field = self.feedback_panel:getChildByName("TextField_2")
	self.Tokefu_editbox= ccui.EditBox:create(cunTemp_field:getContentSize(), ccui.Scale9Sprite:create(""))
	:setFontSize(cunTemp_field:getFontSize())
	:setPosition(cunTemp_field:getPosition())
	:setPlaceHolder("输入问题后发送,客服会在10分钟内给予回复")
	:setMaxLength(100)
	:addTo(cunTemp_field:getParent())
	cunTemp_field:removeFromParent()

	local Image_2 = self.feedback_panel:getChildByName("Image_2")
	
	 local FAQstr = cc.FileUtils:getInstance():getStringFromFile("FAQ.json")
	self.FAQ_tab = {}
	if FAQstr ~= "" then
		self.FAQ_tab = cjson.decode(FAQstr)
	end
 	if scene.kefuRedPointSp:isVisible() then
		self:jumptoChatview()
	else
		self.FAQ_panel:setVisible(true)
		self.feedback_panel:setVisible(false)
		self.feedback_btn:setEnabled(true)
		self.FAQ_btn:setEnabled(false)
	end
	
	local offsetY = ExternalFun.FixViewHeight(self.feedchatList)
	
	ExternalFun.FixNodeOffsetPointY(self.send_btn,offsetY)
	ExternalFun.FixNodeOffsetPointY(self.Tokefu_editbox,offsetY)
	ExternalFun.FixNodeOffsetPointY(Image_2,offsetY)


		self:initFAQpanel()
		self:initChatListview()
end
function KeFuLayer:jumptoChatview()
	self.FAQ_panel:setVisible(false)
	self.feedback_panel:setVisible(true)
	self.feedback_btn:setEnabled(false)
	self.FAQ_btn:setEnabled(true)
	self.scene.kefuRedPointSp:setVisible(false)
	self.scene.kefu_bubble:setVisible(false)
	self.scene._LogonFrame:sendKefuMsg(cc.UserDefault:getInstance():getIntegerForKey("kefuMaxIdx", 0))
end
function KeFuLayer:initFAQpanel()
		self.FAQ_listview = self.FAQ_panel:getChildByName("FAQ_listview")
		self.FAQ_listview:setItemsMargin(10)
		for k,v in ipairs(self.FAQ_tab) do
			item = self:createFAQItem(k-1)
			item:setSwallowTouches(false)
			item:setVisible(true)
			self.FAQ_listview:pushBackCustomItem(item)
		end
		
end
function KeFuLayer:onButtonClickedEvent(tag,ref)
	if tag == KeFuLayer.BT_FAQ then
			
			self.feedback_btn:setEnabled(true)
			self.FAQ_btn:setEnabled(false)

			self.FAQ_panel:setVisible(true)
			self.feedback_panel:setVisible(false)

	elseif tag == KeFuLayer.BT_FEEDBACK then
		self.feedback_btn:setEnabled(false)
		self.FAQ_btn:setEnabled(true)

		self.FAQ_panel:setVisible(false)
		self.feedback_panel:setVisible(true)
		self.scene._LogonFrame:sendKefuMsg(cc.UserDefault:getInstance():getIntegerForKey("kefuMaxIdx", 0))
		
	elseif tag == KeFuLayer.BT_SENDFEEDBACK then
		local feedstr =  trim(self.Tokefu_editbox:getText())
		if feedstr == "" then
			showToast(self,"请输入正确的客服反馈再提交")
			return
		end

		if feedstr ~= "" and trim(feedstr) == "" then
			showToast(self,"请输入正确的客服反馈再提交")
			return
		end

		if feedstr ~= "" and (string.find( feedstr,"\n") or string.find( feedstr,"\r")) then
			showToast(self,"客服消息不能换行,请输入正确的客服反馈再提交")
			return
		end

		local tempstr,_others = ExternalFun.filter_spec_chars(feedstr)
		if _others or (tempstr == ""  and  editstr ~= "") then
			showToast(self,"客服消息不能包含特殊字符")
			-- return
		end
		
		self.scene._LogonFrame:sendSubToKefu(tempstr)
		self.Tokefu_editbox:setText("")
	end
end
function KeFuLayer:sendfeedBackSuccess()
	self.send_btn:setEnabled(false)
	self.sendAtlas:setVisible(true)
	cc.UserDefault:getInstance():setIntegerForKey("feedbacklimit", os.time())
	local sec = 120
	self.sendAtlas:setString(sec)
	self.schedulerID = scheduler:scheduleScriptFunc( function()
            sec = sec - 1
			self.sendAtlas:setString(sec)
            if not tolua.isnull(self.send_btn) then
                
				 
                if sec <= 0 then
                    cc.Director:getInstance():getScheduler():unscheduleScriptEntry(self.schedulerID)
                    self.send_btn:setEnabled(true)
					self.sendAtlas:setVisible(false)
                end        
            end      
        end , 1, false)
end
function KeFuLayer:initChatListview()
	self.feedback_tab = {}
    local feedbackStr = cc.FileUtils:getInstance():getStringFromFile(device.writablePath .."kefuFeedback.txt")

	if not feedbackStr or feedbackStr == "" then
		feedbackStr = cc.FileUtils:getInstance():getStringFromFile("kefuFeedbackDefault.txt")
	end
	self.feedback_tab = cjson.decode(feedbackStr)
		for i =1,#self.feedback_tab do

				if self.feedback_tab[i].typeid == 2 then
					self:FeedBackchat(self.feedback_tab[i],nil)
			elseif self.feedback_tab[i].typeid == 3 then
					self:FeedBackchat(nil,self.feedback_tab[i])
				end
				
			end
			
end

--用于添加listview  item
function KeFuLayer:FeedBackchat(mesadStr,kefuSadStr)
	if kefuSadStr then
		local bglayer = ccui.Layout:create()
--		bglayer:setBackGroundColorType(LAYOUT_COLOR_SOLID)
		bglayer:setOpacity(255)
		bglayer:setBackGroundColor(cc.c3b(144,238,144))
		local kefu_lab = cc.LabelTTF:create(kefuSadStr.content, "",28,
		 cc.size(830,0),
		cc.TEXT_ALIGNMENT_LEFT,
		cc.VERTICAL_TEXT_ALIGNMENT_TOP)
		local kefu_lab_size = kefu_lab:getContentSize()
		kefu_lab:setAnchorPoint(cc.p(0,1))
	--	kefu_lab:setOpacity(200)
		
		local sadbgsize = cc.size(850,kefu_lab_size.height+30)
		local sadbg = ccui.ImageView:create("kefu/kefuinput.png") 
		sadbg:setAnchorPoint(cc.p(1,1))
		sadbg:setScale9Enabled(true)
		sadbg:setContentSize(sadbgsize)
		sadbg:addChild(kefu_lab)
		kefu_lab:setPosition(15,kefu_lab_size.height+15)
		bglayer:setContentSize(992,104+(sadbgsize.height-50))
		bglayer:addChild(sadbg)
		local bglayerSize = bglayer:getContentSize()
		sadbg:setPosition(992,bglayerSize.height-41)
		self.feedchatList:pushBackCustomItem(bglayer)
--时间		
		local time_label = cc.LabelTTF:create(kefuSadStr.createtime, "",24)
		time_label:setAnchorPoint(cc.p(0,1))
		time_label:setPosition(150,bglayerSize.height-15)
		bglayer:addChild(time_label)
		time_label:setOpacity(150)
		
		display.newSprite("kefu/kefujt.png"):move(134,bglayerSize.height-73):addTo(bglayer)
--头像	
		
		local headsp = display.newSprite("kefu/kefuHead.png")
		headsp:setAnchorPoint(cc.p(0,1))
		headsp:setPosition(0,bglayerSize.height)
		bglayer:addChild(headsp)
		
	end
	
	if mesadStr then
		local bglayer = ccui.Layout:create()
	--	bglayer:setBackGroundColorType(LAYOUT_COLOR_SOLID)
		bglayer:setOpacity(255)
		bglayer:setBackGroundColor(cc.c3b(144,238,144))
		local kefu_lab = cc.LabelTTF:create(mesadStr.content, "",28,
		 cc.size(820,0),
		cc.TEXT_ALIGNMENT_LEFT,
		cc.VERTICAL_TEXT_ALIGNMENT_TOP)
		local kefu_lab_size = kefu_lab:getContentSize()
		kefu_lab:setAnchorPoint(cc.p(0,1))
		
		
		local sadbgsize = cc.size(850,kefu_lab_size.height+30)
		local sadbg = ccui.ImageView:create("kefu/myinput.png")
		sadbg:setAnchorPoint(cc.p(0,1))
		sadbg:setScale9Enabled(true)
		sadbg:setContentSize(sadbgsize)
		sadbg:addChild(kefu_lab)
		kefu_lab:setPosition(15,kefu_lab_size.height+15)
		bglayer:setContentSize(992,104+(sadbgsize.height-60))
		bglayer:addChild(sadbg)
		local bglayerSize = bglayer:getContentSize()
		sadbg:setPosition(12,bglayerSize.height-40)
		self.feedchatList:pushBackCustomItem(bglayer)
--时间		
		local time_label = cc.LabelTTF:create(mesadStr.createtime, "",24)
		time_label:setAnchorPoint(cc.p(1,1))
		time_label:setPosition(850,bglayerSize.height-15)
		bglayer:addChild(time_label)
		time_label:setOpacity(150)
		display.newSprite("kefu/myjt.png"):move(870,bglayerSize.height-70):addTo(bglayer)
--头像	
		
		local headsp = HeadSprite:create(HeadSprite.CLIP,GlobalUserItem, 136,"plaza/head_mask3.png")
			local frameFile = nil
		local scaleRate = nil
		frameFile = "plaza/headfram.png"
		scaleRate = 0.75
		headsp:enableHeadFrame(true, {_framefile = frameFile, _scaleRate = scaleRate,_posPer = cc.p(0.5,0.5)})
		headsp:setAnchorPoint(cc.p(1,1))
		headsp:setPosition(1010,bglayerSize.height+15)
		bglayer:addChild(headsp)
		
	end

	if #self.feedchatList:getItems() > 20 then
		self.feedchatList:removeItem(0)
	end
	self.feedchatList:jumpToBottom()
	
	
end
function KeFuLayer:updataChatListview(recJson)

	local maxIdx = cc.UserDefault:getInstance():getIntegerForKey("kefuMaxIdx", 0)
		if recJson and recJson.result ~= 0 then
			for i =1,#recJson.list do
				table.insert(self.feedback_tab,recJson.list[i])
				if recJson.list[i].idx > maxIdx  then
					maxIdx = recJson.list[i].idx
				end
				
				if recJson.list[i].typeid == 2 then
					self:FeedBackchat(recJson.list[i],nil)
				elseif recJson.list[i].typeid == 3 then
					self:FeedBackchat(nil,recJson.list[i])
				end
				
			end
			
		   if self.feedback_panel:isVisible() then
				self.scene.kefuRedPointSp:setVisible(false)
				self.scene.kefu_bubble:setVisible(false)
		   end
		
		end
	cc.UserDefault:getInstance():setIntegerForKey("kefuMaxIdx", maxIdx)
	cc.FileUtils:getInstance():writeStringToFile(cjson.encode(self.feedback_tab),device.writablePath .."kefuFeedback.txt")
	
end
function KeFuLayer:createFAQItem(idx)
	if not self.FAQ_tab[idx+1] then
		return 
	end
	--bg:move(appdf.WIDTH/2,appdf.HEIGHT/2)
	

	local bg = ccui.ImageView:create("kefu/Faqoitem.png")
	bg:setAnchorPoint(cc.p(0,1))
	bg:setScale9Enabled(true)
	local que_text = ccui.Text:create("","",24)  --
	que_text:setAnchorPoint(cc.p(0,1))
	que_text:setTextAreaSize(cc.size(970,0))
	que_text:setString(self.FAQ_tab[idx+1].QUE)

	local que_rendsize = que_text:getVirtualRendererSize()
	que_text:setSize(que_rendsize)
	
	local ANS_text = ccui.Text:create("","",23)  --
	ANS_text:setOpacity(180)
	ANS_text:setAnchorPoint(cc.p(0,1))
	ANS_text:setTextAreaSize(cc.size(970,0))
	ANS_text:setString(self.FAQ_tab[idx+1].ANS)
	local ans_rendsize = ANS_text:getVirtualRendererSize()
	ANS_text:setSize(ans_rendsize)
	
	local bgHeight = ans_rendsize.height + que_rendsize.height+70
	bg:setContentSize(cc.size(1000, bgHeight))
	
	que_text:setPosition(cc.p(20,bgHeight-20))
	bg:addChild(que_text)
	--	que_text:setTextColor(cc.c3b(0,0,0))
	--	ANS_text:setColor(cc.c3b(0,0,0))
	
	ANS_text:setPosition(cc.p(20,bgHeight-que_rendsize.height+5-40))
	bg:addChild(ANS_text)
	
	return bg
end
function KeFuLayer:getLabeiHeight(idx)
	if not self.FAQ_tab[idx+1] then
		return 
	end
	
	local que_text = ccui.Text:create("","fonts/round_body.ttf",24)  --
	
	que_text:setAnchorPoint(cc.p(0,1))
	que_text:setTextAreaSize(cc.size(800,0))
	que_text:setString(self.FAQ_tab[idx+1].QUE)
	local que_rendsize = que_text:getVirtualRendererSize()
	que_text:setSize(que_rendsize)
	
	local ANS_text = ccui.Text:create("","fonts/round_body.ttf",24)  --

	ANS_text:setAnchorPoint(cc.p(0,1))
	ANS_text:setTextAreaSize(cc.size(800,0))
	ANS_text:setString(self.FAQ_tab[idx+1].ANS)
	local ans_rendsize = ANS_text:getVirtualRendererSize()
	ANS_text:setSize(ans_rendsize)
	
	local bgHeight = ans_rendsize.height + que_rendsize.height+10
	
	
	return bgHeight
end




return KeFuLayer